<template>
  <div class="forgot-password-form">
    <div class="form-header">
      <n-text depth="2">请选择找回密码的方式</n-text>
    </div>

    <n-form
      ref="formRef"
      :model="formData"
      :rules="formRules"
      size="large"
      :show-label="false"
    >
      <!-- 邮箱输入 -->
      <n-form-item path="account">
        <n-input
          v-model:value="formData.account"
          placeholder="请输入邮箱地址"
          :disabled="loading"
        >
          <template #prefix>
            <n-icon :size="18">
              <MailOutline />
            </n-icon>
          </template>
        </n-input>
      </n-form-item>

      <!-- 点击验证码 -->
      <n-form-item>
        <ClickCaptcha
          @update:captcha-id="updateCaptchaId"
          @update:captcha-info="updateCaptchaInfo"
          @verified="handleCaptchaVerified"
          :disabled="loading"
        />
      </n-form-item>

      <!-- 邮箱验证码 -->
      <n-form-item path="captcha">
        <div class="captcha-container">
          <n-input
            v-model:value="formData.captcha"
            placeholder="请输入邮箱验证码"
            :disabled="loading"
          >
            <template #prefix>
              <n-icon :size="18">
                <ShieldCheckmarkOutline />
              </n-icon>
            </template>
          </n-input>
          <n-button
            :disabled="loading || countdown > 0 || !formData.account || !captchaVerified"
            :loading="sendingCode"
            @click="sendVerificationCode"
            class="send-code-btn"
          >
            {{ countdown > 0 ? `${countdown}s` : '发送验证码' }}
          </n-button>
        </div>
      </n-form-item>

      <!-- 新密码 -->
      <n-form-item path="password">
        <n-input
          v-model:value="formData.password"
          type="password"
          placeholder="请输入新密码"
          :disabled="loading"
          show-password-on="click"
        >
          <template #prefix>
            <n-icon :size="18">
              <LockClosedOutline />
            </n-icon>
          </template>
        </n-input>
      </n-form-item>

      <!-- 确认新密码 -->
      <n-form-item path="confirmPassword">
        <n-input
          v-model:value="formData.confirmPassword"
          type="password"
          placeholder="请确认新密码"
          :disabled="loading"
          show-password-on="click"
        >
          <template #prefix>
            <n-icon :size="18">
              <LockClosedOutline />
            </n-icon>
          </template>
        </n-input>
      </n-form-item>

      <n-button
        type="primary"
        size="large"
        block
        :loading="loading"
        :disabled="loading"
        @click="handleSubmit"
        class="submit-btn"
      >
        重置密码
      </n-button>
    </n-form>

    <div class="form-footer">
      <n-button
        text
        type="primary"
        :disabled="loading"
        @click="$emit('back-to-login')"
      >
        返回登录
      </n-button>
    </div>
  </div>
</template>

<script lang="ts" setup>
import { ref, reactive, computed } from 'vue'
import { useMessage } from 'naive-ui'
import { retrievePassword } from '@/api/account'
import { sendEmailCode } from '@/api/user'
import { commonRules, createConfirmPasswordRules } from '@/utils/validation'
import { generateRandomString } from '@/utils/auth'
import ClickCaptcha from '@/components/common/ClickCaptcha.vue'
import type { FormInst } from 'naive-ui'
import type { ForgotPasswordParams } from '@/types/user'
import {
  MailOutline,
  LockClosedOutline,
  ShieldCheckmarkOutline
} from '@vicons/ionicons5'

interface Emits {
  (e: 'success'): void
  (e: 'back-to-login'): void
}

const emit = defineEmits<Emits>()
const message = useMessage()

// 表单引用
const formRef = ref<FormInst | null>(null)

// 表单数据
const formData = reactive<ForgotPasswordParams>({
  type: 'email',
  account: '',
  captcha: '',
  password: '',
  confirmPassword: ''
})

// 验证码相关数据
const captchaId = ref(generateRandomString())
const captchaInfo = ref('')

// 状态
const loading = ref(false)
const sendingCode = ref(false)
const countdown = ref(0)
const captchaVerified = ref(false)

// 表单验证规则
const formRules = computed(() => ({
  account: commonRules.email,
  captcha: commonRules.captcha,
  password: commonRules.password,
  confirmPassword: createConfirmPasswordRules(() => formData.password)
}))

// 更新验证码ID
const updateCaptchaId = (id: string) => {
  captchaId.value = id
}

// 更新验证码信息
const updateCaptchaInfo = (info: string) => {
  captchaInfo.value = info
}

// 处理验证码验证成功
const handleCaptchaVerified = (verified: boolean) => {
  captchaVerified.value = verified
}

// 发送验证码
const sendVerificationCode = async () => {
  if (!formRef.value) return

  // 检查点击验证码是否已验证
  if (!captchaVerified.value) {
    message.error('请先完成点击验证码验证')
    return
  }

  // 验证邮箱字段
  try {
    await formRef.value.validate(undefined, (rule) => rule.key === 'account')
  } catch {
    return
  }

  try {
    sendingCode.value = true

    // 发送邮箱验证码，需要传递点击验证码信息
    await sendEmailCode(formData.account, 'user_retrieve_pwd', {
      captchaId: captchaId.value,
      captchaInfo: captchaInfo.value
    })

    message.success('验证码已发送')
    startCountdown()
  } catch (error: any) {
    console.error('发送验证码失败:', error)
    message.error(error.message || '发送验证码失败')
  } finally {
    sendingCode.value = false
  }
}

// 开始倒计时
const startCountdown = () => {
  countdown.value = 60
  const timer = setInterval(() => {
    countdown.value--
    if (countdown.value <= 0) {
      clearInterval(timer)
    }
  }, 1000)
}

// 提交表单
const handleSubmit = async () => {
  if (!formRef.value || loading.value) return

  try {
    await formRef.value.validate()

    loading.value = true

    // 构建API请求参数，排除confirmPassword字段
    const { confirmPassword, ...apiParams } = formData
    console.log('提交找回密码请求，参数:', apiParams)

    await retrievePassword(apiParams)
    message.success('密码重置成功')
    emit('success')
  } catch (error: any) {
    console.error('重置密码失败:', error)
    message.error(error.message || '重置密码失败，请重试')
  } finally {
    loading.value = false
  }
}


</script>

<style scoped>
.forgot-password-form {
  padding: 8px 0;
}

.form-header {
  text-align: center;
  margin-bottom: 24px;
}

.captcha-container {
  display: flex;
  gap: 12px;
  align-items: center;
}

.captcha-container .n-input {
  flex: 1;
}

.send-code-btn {
  white-space: nowrap;
  min-width: 100px;
}

.submit-btn {
  margin-top: 8px;
  border-radius: 8px;
  font-weight: 500;
}

.form-footer {
  display: flex;
  justify-content: center;
  margin-top: 24px;
  padding-top: 16px;
  border-top: 1px solid var(--n-border-color);
}

/* 响应式调整 */
@media (max-width: 480px) {
  .captcha-container {
    gap: 8px;
  }
  
  .send-code-btn {
    min-width: 80px;
    font-size: 12px;
  }
  
  .form-footer {
    margin-top: 20px;
    padding-top: 12px;
  }
}
</style>
